<template>
  <el-card class="box-card" shadow="hover">
    <div slot="header" class="clearfix">
      <el-button type="primary" size="small" @click="openDialog"
        ><i class="el-icon-plus"></i> 添加品牌</el-button
      >
    </div>
    <!-- 表格展示 -->
    <el-table
      :data="trademarkList"
      border
      :row-key="
        (row) => {
          return row.id;
        }
      "
    >
      <el-table-column type="index" label="序号" width="100px" align="center">
      </el-table-column>
      <el-table-column prop="tmName" label="品牌名称" align="center">
      </el-table-column>
      <el-table-column label="品牌LOGO" align="center">
        <template v-slot="{ row }">
          <el-image style="height: 100px" :src="row.logoUrl"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200">
        <template v-slot="{ row }">
          <el-button
            type="warning"
            class="el-icon-edit"
            size="mini"
            @click="openDialog(row)"
          />
          <el-button type="danger" class="el-icon-delete" size="mini" @click="deleteTrademark(row.id)" />
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      class="pagination-margin"
      @size-change="updatePageSize"
      @current-change="updatePage"
      :current-page="page"
      :page-sizes="[3, 6, 9]"
      :page-size="pageSize"
      layout=" prev, pager, next, jumper, -> , sizes, total"
      :total="total"
    >
    </el-pagination>
    <!-- 添加或修改 对话框 -->
    <el-dialog
      :title="`${formData.id ? '修改' : '添加'}品牌`"
      :visible.sync="dialogVisible"
      :before-close="handleClose"
    >
      <el-form
        label-width="100px"
        :rules="formDataRules"
        :model="formData"
        ref="formRef"
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input
            placeholder="请输入内容"
            size="small"
            style="width: 400px"
            v-model="formData.tmName"
          />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <!-- 上传图片 -->
          <el-upload
            class="avatar-uploader"
            :action="`${BASEURL}/admin/product/upload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="formData.logoUrl"
              :src="formData.logoUrl"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div class="el-upload__tip" slot="tip">
              只能上传jpg/png/gif文件，且不超过2M
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
        <el-button
          type="primary"
          @click.prevent="addOrUpdateTrademark"
          size="small"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import { mapActions, mapState } from "vuex";
export default {
  name: "Trademark",
  data() {
    return {
      page: 1,
      pageSize: 3,
      dialogVisible: false,
      BASEURL: process.env.VUE_APP_BASE_API,
      formDataRules: {
        tmName: [
          { required: true, message: "请输入品牌名称", trigger: "blur" },
        ],
        logoUrl: [{ required: true, message: "请上传品牌LOGO" }],
      },
      formData: {
        id: 0,
        tmName: "",
        logoUrl: "",
      },
    };
  },
  mounted() {
    this.getTrademarkList({ page: this.page, pageSize: this.pageSize });
  },
  methods: {
    ...mapActions({
      getTrademarkList: "trademark/getTrademarkList",
    }),
    // 分页器
    updatePage(page) {
      this.page = page;
      this.getTrademarkList({ page: this.page, pageSize: this.pageSize });
    },
    updatePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTrademarkList({ page: this.page, pageSize: this.pageSize });
    },
    // 取消按钮
    handleClose() {
      this.dialogVisible = false;
    },
    // 图片上传
    handleAvatarSuccess(res, file) {
      this.formData.logoUrl = URL.createObjectURL(file.raw);
      this.$refs.formRef.clearValidate(["logoUrl"]);
    },
    beforeAvatarUpload(file) {
      const imgType = ["image/jpeg", "image/png", "image/gif"];
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!imgType.some((item) => item === file.type)) {
        this.$message.error("上传的图片只能是 JPG / PNG / GIF 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return imgType && isLt2M;
    },
    // 清空表单数据 函数
    resetFormData() {
      this.formData = { id: 0, tmName: "", logoUrl: "" };
    },
    // 添加品牌按钮/编辑按钮
    openDialog(row) {
      this.formData = row;
      this.dialogVisible = true;
      if (!row.id) {
        // 重置表单数据
        this.resetFormData();
      }
      // 清空表单校验结果
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 添加/修改 品牌
    async addOrUpdateTrademark() {
      await this.$refs.formRef.validate();
      if (!this.formData.id) {
        const { logoUrl, tmName } = this.formData;
        await this.$api.addTrademark({ logoUrl, tmName });
      } else {
        await this.$api.updateTrademark(this.formData);
      }
      this.$message({
        message: `${this.formData.id ? "修改" : "添加"}品牌成功`,
        type: "success",
      });
      this.dialogVisible = false;
      this.getTrademarkList({ page: this.page, pageSize: this.pageSize });
    },
    // 删除品牌
    async deleteTrademark(id){
      await this.$api.deleteTrademark(id)
      this.$message({
        message:'删除成功',
        type:'success'
      })
      this.getTrademarkList({ page: this.page, pageSize: this.pageSize });
    }
  },
  computed: {
    ...mapState("trademark", ["trademarkList", "total"]),
  },
};
</script>

<style lang="scss" scoped>
.pagination-margin {
  margin-top: 20px;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
